package com.igeek.shop.web.gouwuche;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.igeek.common.utils.CommonUtils;
import com.igeek.shop.entity.Cart;
import com.igeek.shop.entity.CartItem;
import com.igeek.shop.entity.Gouwuche;
import com.igeek.shop.entity.Order;
import com.igeek.shop.entity.OrderItem;
import com.igeek.shop.entity.Product;
import com.igeek.shop.entity.User;
import com.igeek.shop.service.ProductService;
import com.igeek.shop.service.gouwuche.CartService;
import com.igeek.shop.service.gouwuche.CartServiceImp;

public class CartServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private CartService cartservice = new CartServiceImp();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		String state = req.getParameter("state");
		if (state.equals("add")) {
			// 添加购物车
			add(req, resp);
		} else if (state.equals("delect")) {
			// 删除单个商品
			delect(req, resp);
		} else if (state.equals("clearCart")) {
			// 清空购物车
			clearCart(req, resp);
		} else if (state.equals("submitOrder")) {
			//提交订单的同时清空购物车
			submitOrder(req, resp);
		}else if (state.equals("direct")){
			direct(req,resp);
		}

	}

	
	//点击购物车按钮时，可直接看到用户之前在购物车中添加的商品
	private void direct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		User user = (User) req.getSession().getAttribute("user");
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		cart = new Cart();
		String username = user.getUsername();
		// 拿到该用户购物车中所有的信息
		double total = 0;
		List<Gouwuche> gouwuche = cartservice.all(username);
		for (Gouwuche gouwu : gouwuche) {
			Product product1 = cartservice.query(gouwu.getPid());
			CartItem item1 = new CartItem(product1, gouwu.getBuyNum(), gouwu.getsubtotal());
			cart.getList().put(product1.getPid(), item1);
			total = total + item1.getSubTotal();
			
	}
		cart.setTotal(total);
		req.getSession().setAttribute("cart", cart);
		req.getRequestDispatcher("/cart.jsp").forward(req, resp);
}
	
	


	/*
	 * 提交订单
	 */
	private void submitOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpSession session = req.getSession();

		// 验证用户是否登录
		User user = (User) session.getAttribute("user");
		if (user == null) {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}

		// 创建Order对象
		Order order = new Order();

		// 属性封装

		String oid = CommonUtils.getUUID();
		order.setOid(oid);
		// 下单时间
		order.setOrdertime(new Date());
		// 总金额

		// 获取购物车
		Cart cart = (Cart) session.getAttribute("cart");
		// 处理详细逻辑（省略）
		order.setTotal(cart.getTotal());

		// 设置购买用户
		order.setUser(user);

		// 设List<OrderItem>orderitems；
		// 从购物车中获取CartItem转成OrderItem();
		Map<String, CartItem> list = cart.getList();

		for (Entry<String, CartItem> entry : list.entrySet()) {
			// 得到每一个购物项
			CartItem cartItem = entry.getValue();

			// 准备OrderItem,从CartItem转换数据
			OrderItem orderitem = new OrderItem();
			orderitem.setItemid(CommonUtils.getUUID());
			orderitem.setCount(cartItem.getBuyNum());
			orderitem.setSubtotal(cartItem.getSubTotal());
			orderitem.setProduct(cartItem.getProduct());
			orderitem.setOrder(order);

			// 将订单项存入到order中的订单项的集合中
			order.getOrderItems().add(orderitem);
		}

		// 调用service层 方法
		ProductService service = new ProductService();
		service.submitOrders(order);

		// order存到session
		session.setAttribute("order", order);
		
		// 跳转
		req.getRequestDispatcher("/order_info.jsp").forward(req, resp);
	}

	private void clearCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.getSession().removeAttribute("cart");
		cartservice.clearCart();
		req.getRequestDispatcher("/cart.jsp").forward(req, resp);
	}

	private void delect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String pid = req.getParameter("pid");
		pid.trim();
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		if (cart != null) {
			Map<String, CartItem> list = cart.getList();
			double total = cart.getTotal();
			double ydf = list.get(pid).getSubTotal();
			total = total - ydf;
			cart.setTotal(total);
			list.remove(pid);
			cartservice.delete(pid);
			req.getSession().setAttribute("cart", cart);
			resp.sendRedirect(req.getContextPath() + "/cart.jsp");
			// req.getRequestDispatcher("/cart.jsp").forward(req, resp);
		}
	}

	private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub

		// 判断有无用户，有用户登陆时才能提交订单
		User user = (User) req.getSession().getAttribute("user");
		double total =0;
		// 每次提交订单时，将数据存入数据库，这样不同的用户登陆时，便能看到自己专属的购物车

		// 判断域中是否有购物车的信息
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		if (user != null) {

			if (cart == null) {
				// 第一次加购
				cart = new Cart();
				String username = user.getUsername();
				// 拿到该用户购物车中所有的信息
				List<Gouwuche> gouwuche = cartservice.all(username);
				for (Gouwuche gouwu : gouwuche) {
					Product product1 = cartservice.query(gouwu.getPid());
					CartItem item1 = new CartItem(product1, gouwu.getBuyNum(), gouwu.getsubtotal());
					cart.getList().put(product1.getPid(), item1);
					 total = total + gouwu.getsubtotal();
				}
			}

			// 获取商品id
			String pid = req.getParameter("pid");
			pid.trim();

			// 获取加入购物车的数量
			String quantity = req.getParameter("quantity");

			int qt = Integer.parseInt(quantity);
			Product product = cartservice.query(pid);

			double money = product.getShop_price();

			// 计算小计
			double subtotal = qt * money;

			// 将通过id得到的商品信息，商品数量，和小计添加到Cartitem实体类中
			CartItem item = new CartItem(product, qt, subtotal);
			item.setSubTotal(subtotal);

			Map<String, CartItem> list = cart.getList();

			if (list.containsKey(pid)) {
				// 重复商品，需要合并
				int oldNum = list.get(pid).getBuyNum();
				qt += oldNum;
				item.setBuyNum(qt);
				double newwith = qt * money;
				item.setSubTotal(newwith);
				cartservice.SetNumber(pid, qt, newwith);
			} else {
				cartservice.save(pid, qt, subtotal, user.getUsername());
			}

			// 将CartItem存到cart购物车中，相当于商品的一切信息
			cart.getList().put(product.getPid(), item);

			// 计算总计，设置到cart中
			total = total+cart.getTotal() + subtotal;
			cart.setTotal(total);

			req.getSession().setAttribute("cart", cart);
			req.getRequestDispatcher("/cart.jsp").forward(req, resp);
		} else {
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}

	}

}
